var express = require('express')
var router = express.Router()
let User=require("../models/user")
let rspMsg={}

// middleware that is specific to this router   //router.user是用来干什么的
router.use(function timeLog (req, res, next) {
    console.log('Time: ', Date.now())
    rspMsg={
        code:0,
        msg:''
    }
    next()
})
// define the home page route
router.get('/', function (req, res) {
    res.send('api')
})
// define the about route
router.get('/about', function (req, res) {
    res.send('About api')
})

router.post('/account/register',async function (req,res,next){
   //console.log(req.body);
    let username=req.body.username;
    let password=req.body.password;
    let passWordAgain=req.body.passwordAgain;
    let isExitAdmin =await User.findOne({isAdmin:"false"},function (err){});
    //用户是否存在
    const user =await User.findOne({userName:username});
    if (user){
        res.send({"msg":"exist"});
    }else {
        if(!isExitAdmin){
            new User ({userName:username,passWord:password,isAdmin:true}).save();
        }else {
            new User ({userName:username,passWord:password,isAdmin:false}).save();
        }
        res.send({"msg":"success"});
    }
})
router.get('/login' ,function (req,res){
    res.render('./main/login')
})
router.get('/register',function (req,res){
    res.render('./main/register')
})
router.post('/account/login',async function (req,res,next){
    let username=req.body.username;
    let password=req.body.password;
    //用户是否存在
    const userFromDb =await User.findOne({userName:username});
    if (userFromDb){
        rspMsg.user=userFromDb;
        rspMsg.code="200";
        rspMsg.msg='登陆成功'
        req.cookies.set("__user",JSON.stringify({
            _id:userFromDb._id,
        }));
    }else {
        rspMsg.user=userFromDb;
        rspMsg.code="201";
        rspMsg.msg='登陆失败'
       // res.send({"msg":"success"});
    }
    res.send(rspMsg);
})


router.get('/account/logout',async function (req,res,next){
        rspMsg.code="300";

        req.cookies.set("__user",null)

    res.render("./main/article",{
        rspMsg:rspMsg
    });
})


module.exports = router